package hhm.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanUtils {

	public Object combine(Object oldObject, Object newObject) throws SecurityException, NoSuchMethodException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {

		Field[] newField = newObject.getClass().getDeclaredFields();
		Field[] oldField = oldObject.getClass().getDeclaredFields();

		for (int j = 0; j < newField.length; j++) { // 遍历所有属性
			String name = newField[j].getName(); // 获取属性的名字
			// 将属性的首字符大写，方便构造get，set方法
			name = name.substring(0, 1).toUpperCase() + name.substring(1);

			// 遇到序列化的成员变量就跳过
			if (name.equals("SerialVersionUID")) {
				continue;
			}
			Method oldMethod = oldObject.getClass().getMethod("get" + name);
			Object oldValue = null;

			String methodname = newField[j].getGenericType().toString();
			if (methodname.contains("Timestamp")) {
				oldValue = oldMethod.invoke(oldObject);
			} else if (methodname.contains("Integer")) {
				oldValue = oldMethod.invoke(oldObject);
			} else if (methodname.contains("String")) {
				oldValue = oldMethod.invoke(oldObject);
			}

			Method newMethod = newObject.getClass().getMethod("get" + name);
			Object newValue = null;

			if (methodname.contains("Timestamp")) {
				newValue = newMethod.invoke(newObject);
			} else if (methodname.contains("Integer")) {
				newValue = newMethod.invoke(newObject);
			} else if (methodname.contains("String")) {
				newValue = newMethod.invoke(newObject);
			}

			if (newValue != null) {
				// 证明要覆盖掉旧的
				String oldName = oldField[j].getName(); // 获取属性的名字
				oldName = oldName.substring(0, 1).toUpperCase() + oldName.substring(1);

				Class<?> classtype = Class.forName(oldField[j].getGenericType().toString().replace("class", "").trim());
				newMethod = newObject.getClass().getMethod("set" + oldName, classtype);

				newMethod.invoke(oldObject, newValue);

			}

		}

		return oldObject;

	}
}
